// pages/addressEdit/addressEdit.js
import { reqAddressByaddressid, reqAddressListByuserid, updateDefaultAddress, reqUpdateAddress, reqAddAddress } from '../../api/address';

Page({
  data: {
    ifhas: false,//是否手动输入
    location: {
      name: ' ',
      address: ' '
    },
    name: '',
    phone: '',
    region: ['', '', ''],
    detail: '',
    addressid: '', // 地址 ID
    isEdit: false, // 是否是编辑模式
    userid: '', // 用户 ID
    textData: '',
    distance: '',//距离
    duration: '',//时间
    mi: '',
    isDefault: false
  },
  
  onChange({ detail }) {
    this.setData({ isDefault: detail });
    console.log("isDefault::::" + detail);
  },
  
  //前往地图 
  gotomap() {
    const then = this;
    wx.navigateTo({
      url: '/pages/getmap/getmap',
      events: {
        backEvent: function (data) {
          console.log('收到数据：', data)
          const region = [
            data.obj.pname,
            data.obj.cityname,
            data.obj.adname
          ]
          then.setData({
            textData: data.obj,
            distance: data.distance,
            duration: data.duration,
            mi: data.mi,
            region,
            'location.address': data.obj.pname + "/" + data.obj.cityname + "/" + data.obj.adname,
            detail: data.obj.name
          })
        }
      }
    })
  },
  
  onLoad: function (options) {
    if (options.addressid) {
      wx.setNavigationBarTitle({ title: '编辑收货地址' });
    } else {
      wx.setNavigationBarTitle({ title: '新增收货地址' });
    }
    
    console.log("获取id：", options);
    const addressid = options.addressid;
    console.log(addressid);
    
    // 从本地存储中获取用户信息
    const userInfo = wx.getStorageSync('userinfo');
    if (userInfo && userInfo.userid) {
      this.setData({ userid: userInfo.userid });
    } else {
      wx.showToast({
        title: '未获取到用户信息',
        icon: 'none'
      });
    }
    
    // 判断是新增还是修改
    if (addressid) {
      this.setData({
        isEdit: true,
        addressid: addressid,
      });
      this.getAddressById(addressid);
    } else {
      this.setData({ isEdit: false });
    }
  },

  // 保存方法【新增/修改】
  saveAddress: function () {
    console.log("这是saveAddress方法");
    const { name, phone, region, detail, isDefault, addressid, isEdit, userid } = this.data;
    
    // 验证表单数据
    if (!name || !phone || !region[0] || !region[1] || !region[2] || !detail) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    
    // 手机号格式验证
    if (!this.validatePhone(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    
    // 处理事件通道（避免undefined错误）
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.emit('backEvent', {
        obj: this.data.textData,
        distance: this.data.distance,
        duration: this.data.duration,
        mi: this.data.mi
      });
    }
    
    // 如果需要设置为默认地址，先检查是否已有默认地址
    if (isDefault) {
      this.checkExistingDefaultAddress(userid, addressid, isEdit)
        .then(canProceed => {
          if (canProceed) {
            this.submitAddress(addressid, isEdit, userid, {
              name, phone, region, detail, isDefault
            });
          }
        });
    } else {
      // 不设置为默认地址，直接提交
      this.submitAddress(addressid, isEdit, userid, {
        name, phone, region, detail, isDefault
      });
    }
  },
  
  // 检查是否已有默认地址
  checkExistingDefaultAddress: function (userid, currentAddressId, isEdit) {
    return new Promise((resolve) => {
      wx.showLoading({ title: '检查默认地址...' });
      
      // 调用API获取用户所有地址
      reqAddressListByuserid(userid)
        .then(res => {
          wx.hideLoading();
          
          if (res.code === 200 && res.data && res.data.selectAddressByUserid) {
            // 查找已有的默认地址（defaultaddress=0）
            const existingDefault = res.data.selectAddressByUserid.find(addr => 
              addr.defaultaddress === 0 && 
              // 编辑模式下排除当前地址自身
              !(isEdit && addr.addressid === currentAddressId)
            );
            
            if (existingDefault) {
              // 已有默认地址，询问用户是否替换
              wx.showModal({
                title: '提示',
                content: '您已存在默认地址，是否将当前地址设为默认并取消原默认地址？',
                confirmText: '确定',
                cancelText: '取消',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    // 用户确认替换，先将原有默认地址设为非默认
                    this.updateOldDefaultAddress(existingDefault.addressid)
                      .then(() => resolve(true))
                      .catch(() => resolve(false));
                  } else {
                    // 用户取消，不设置为默认地址
                    this.setData({ isDefault: false });
                    resolve(true); // 继续保存，但不设置为默认
                  }
                }
              });
            } else {
              // 没有已有默认地址，可以直接设置
              resolve(true);
            }
          } else {
            // 没有地址数据或接口返回异常，允许设置
            resolve(true);
          }
        })
        .catch(err => {
          wx.hideLoading();
          console.error('获取地址列表失败:', err);
          wx.showToast({ title: '检查默认地址失败', icon: 'none' });
          resolve(false);
        });
    });
  },
  
  // 将原有默认地址设为非默认
  updateOldDefaultAddress: function (oldAddressId) {
    return new Promise((resolve) => {
      wx.showLoading({ title: '更新默认地址...' });
      // 调用修改默认地址API，将原有默认地址设为非默认（1）
      updateDefaultAddress(1, oldAddressId)
        .then(res => {
            console.log("修改默认地址："+res);
          wx.hideLoading();
          if (res === 1) {
            // 更新成功
            resolve(true);
          } else {
            wx.showToast({ title: '更新原有默认地址失败', icon: 'none' });
            resolve(false);
          }
        })
        .catch(err => {
          wx.hideLoading();
          console.error('更新原有默认地址失败:', err);
          wx.showToast({ title: '更新默认地址失败', icon: 'none' });
          resolve(false);
        });
    });
  },
  
  // 提交地址数据（新增或更新）
  submitAddress: function (addressid, isEdit, userid, formData) {
    const { name, phone, region, detail, isDefault } = formData;
    
    // 准备请求数据
    const addressData = {
      consignee: name,
      phone: phone,
      province: region[0],
      city: region[1],
      district: region[2],
      address: detail,
      isDefault: isDefault ? 0 : 1,
      distance: this.data.distance,
      duration: this.data.duration,
      cmorkm: this.data.mi,
      defaultaddress: isDefault ? 0 : 1
    };
  
    if (isEdit) {
      // 编辑模式 - 更新已有地址
      addressData.addressid = addressid;
      this.updateAddress(addressData);
    } else {
      // 新增模式 - 创建新地址
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.emit('backEvent', {
          name: name,
          phone: phone,
          province: this.data.textData?.pname,
          city: this.data.textData?.cityname,
          district: this.data.textData?.adname,
          detail: detail,
          obj: this.data.textData,
          distance: this.data.distance,
          duration: this.data.duration,
          mi: this.data.mi
        });
      }
      addressData.userid = userid;
      this.createAddress(addressData);
    }
  },

  // 根据地址 ID 获取地址信息
  getAddressById: function (addressid) {
    reqAddressByaddressid(addressid)
      .then(res => {
        console.log("完整API响应:", res);
        // 根据defaultaddress设置isDefault
        console.log("这个地址的是否是默认的：" + res.data.selectAddressById.defaultaddress);
        const isDefault = res.data.selectAddressById.defaultaddress === 0;
        this.setData({ isDefault: isDefault });
  
        if (res.code === 200) {
          const address = res.data.selectAddressById ||
            res.data.address ||
            res.data[0] ||
            {};
          this.setData({
            name: address.consignee || '',
            phone: address.phone || '',
            region: [
              address.province || '湖南省',
              address.city || '长沙市',
              address.district || address.area || '天心区'
            ],
            detail: address.address || '',
          });
          this.syncLocation();
        } else {
          throw new Error(res.msgerr || '加载地址信息失败');
        }
      })
      .catch(err => {
        console.error('加载地址信息失败:', err);
      });
  },
  
  // 更新地址
  updateAddress: function (addressData) {
    console.log("传给后端的更新参数：", addressData);
    wx.showLoading({ title: '保存中...' });
    reqUpdateAddress(addressData)
      .then(res => {
        wx.hideLoading();
        if (res === 1) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msgerr || '修改地址失败');
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('修改地址失败:', err);
        wx.showToast({
          title: err.message || '修改地址失败',
          icon: 'none'
        });
      });
  },

  // 新增地址
  createAddress: function (addressData) {
    wx.showLoading({ title: '保存中...' });
    reqAddAddress(addressData)
      .then(res => {
        wx.hideLoading();
        if (res === 1) {
          wx.showToast({
            title: '新增成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msgerr || '新增地址失败');
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('新增地址失败:', err);
        wx.showToast({
          title: err.message || '新增地址失败',
          icon: 'none'
        });
      });
  },

  // 同步上方地址显示
  syncLocation: function () {
    const { region, detail } = this.data;
    const province = region[0] || '';
    const city = region[1] || '';
    const district = region[2] || '';

    this.setData({
      location: {
        name: detail || '未填写详细地址',
        address: `${province}/${city}/${district}`
      }
    });
  },

  // 手机号验证函数
  validatePhone(phone) {
    const reg = /^1[3-9]\d{9}$/;
    return reg.test(phone);
  },

  onNameInput: function (e) {
    this.setData({ name: e.detail.value });
  },

  onPhoneInput: function (e) {
    const value = e.detail.value;
    const phone = value.replace(/[^0-9]/g, '');
    if (phone.length > 11) {
      this.setData({ phone: phone.slice(0, 11) });
      return;
    }
    this.setData({ phone: phone });

    if (phone.length === 11 && !this.validatePhone(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none',
        duration: 1500
      });
    }
  },

  onRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      ifhas: true
    }, () => {
      this.syncLocation();
    });
  },

  onDetailInput: function (e) {
    this.setData({
      detail: e.detail.value,
      ifhas: true
    }, () => {
      this.syncLocation();
    });
  },
});